package com.tofch.biproject.mq;

import com.rabbitmq.client.Channel;
import com.tofch.biproject.common.ErrorCode;
import com.tofch.biproject.manager.AiManager;
import com.tofch.biproject.model.entity.Chart;
import com.tofch.biproject.service.ChartService;
import com.tofch.biproject.exception.BusinessException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.tofch.biproject.constant.AIConstant.biModeId;

@Component
@Slf4j
public class BiMessageConsumer {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("信息真正消费");
        if(StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }

        //调用AI
        //先修改图表任务状态为执行中，等执行完成后修改为”succeed,保存结果，失败抛异常，记录错误信息
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart ==null){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"图表为空");

        }

        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "图表状态更新失败");
            return;
        }

        String userInputResut = buildUserInput(chart);

        String endtResult = aiManager.doChart(userInputResut, biModeId);

        String[] splits = endtResult.split("【【【【【");

        if (splits.length < 2) {
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);

        updateChartResult.setStatus("succeed");
        boolean b1 = chartService.updateById(updateChartResult);
        if (!b1) {
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        log.info("meaage = {}", message);
        //消息确认
        channel.basicAck(deliveryTag, false);
    }



    private String buildUserInput(Chart chart){

        //用户输入目标
        StringBuilder userInput = new StringBuilder();

        userInput.append("需求分析：").append(chart.getGoal()).append("\n");

        userInput.append("图表类型：").append(chart.getChartType()).append("\n");

        userInput.append("原始数据：").append(chart.getChartData()).append("\n");

        String userInputResut = userInput.toString();

        return userInputResut;
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        chartService.updateById(updateChartResult);

    }
}
